package com.marion.langchain4jdemo.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import com.marion.langchain4jdemo.model.RepairRecord;
import org.springframework.ai.tool.annotation.Tool;
import org.springframework.ai.tool.annotation.ToolParam;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;

/**
 * 维修记录服务类
 */
@Slf4j
@Service
public class RepairRecordService {

    private static final String REPAIR_RECORD_URL = "http://teamx-club-webinternal.dockeruat.lefile.cn/openapi/services/serviceOrderPage";

    /**
     * 工单类型常量
     */
    public static final class ServiceOrderType {
        public static final int ACTIVE = 0;    // 活动进行中工单
        public static final int HISTORY = 1;   // 历史已完成工单
    }

    private final RestTemplate restTemplate;

    public RepairRecordService(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    @Tool(description = "查询用户维修记录")
    public List<RepairRecord> getRepairRecords(
            @ToolParam(required = false, description = "用户手机号ID，默认不传") String bindMobileId,
            @ToolParam(required = false, description = "页码，默认1") Integer pageIndex,
            @ToolParam(required = false, description = "每页记录数，默认10") Integer pageSize,
            @ToolParam(required = true, description = "服务订单类型(0:活动进行中工单, 1:历史已完成工单)") Integer serviceOrderType,
            @ToolParam(required = true, description = "用户ID") String lenovoUid) {
        
        // 设置默认值
        pageIndex = pageIndex == null ? 1 : pageIndex;
        pageSize = pageSize == null ? 10 : pageSize;
        
        log.info("Querying repair records for user: {}, page: {}, pageSize: {}, serviceOrderType: {}", 
                lenovoUid, pageIndex, pageSize, serviceOrderType);
        List<RepairRecord> records = new ArrayList<>();
        
        try {
            // 构建请求URL
            String url = String.format("%s?pageIndex=%d&pageSize=%d&serviceOrderType=%d&mock=false",
                    REPAIR_RECORD_URL, pageIndex, pageSize, serviceOrderType);
            
            // 如果提供了bindMobileId，则添加到URL中
            if (bindMobileId != null && !bindMobileId.trim().isEmpty()) {
                url += "&bindMobileId=" + bindMobileId;
            }

            // 设置请求头
            HttpHeaders headers = new HttpHeaders();
            headers.set("X-Lenovo-UID", lenovoUid);
            headers.set("User-Agent", "Apifox/1.0.0 (https://apifox.com)");
            HttpEntity<?> requestEntity = new HttpEntity<>(headers);
            
            // 发起HTTP GET请求
            ResponseEntity<String> response = restTemplate.exchange(
                    url,
                    HttpMethod.GET,
                    requestEntity,
                    String.class
            );
            
            String responseBody = response.getBody();
            log.info("Repair records response: {}", responseBody);

            // 解析JSON响应
            JSONObject jsonObject = JSON.parseObject(responseBody);
            if (jsonObject.getInteger("status") == 0) {
                JSONObject res = jsonObject.getJSONObject("res");
                JSONArray rows = res.getJSONArray("rows");

                // 将rows数组映射为RepairRecord列表
                if (rows != null) {
                    for (int i = 0; i < rows.size(); i++) {
                        JSONObject item = rows.getJSONObject(i);
                        RepairRecord record = new RepairRecord();
                        record.setSoId(item.getString("soId"));
                        record.setServiceOrderType(item.getInteger("serviceOrderType"));
                        record.setAppointmentType(item.getInteger("appointmentType"));
                        record.setAppointmentTypeDes(item.getString("appointmentTypeDes"));
                        record.setOrderDetailTip(item.getString("orderDetailTip"));
                        record.setOrderDetailUrl(item.getString("orderDetailUrl"));
                        record.setActualServiceMode(item.getString("actualServiceMode"));
                        record.setOrderStatus(item.getString("orderStatus"));
                        record.setFaultDescription(item.getString("faultDescription"));
                        record.setHopeServiceNameAndTime(item.getString("hopeServiceNameAndTime"));
                        record.setProductName(item.getString("productName"));
                        records.add(record);
                    }
                }
            } else {
                log.error("Failed to get repair records, status: {}", jsonObject.getInteger("status"));
            }
        } catch (Exception e) {
            log.error("Error occurred while querying repair records: {}", e.getMessage(), e);
        }
        
        return records;
    }
} 
